//
//  BMSAPIService.m
//  BMSSDK
//
//  Created by YeJary on 2025/4/27.
//

#import "BMSAPIService.h"
#import "BMSNetworkSessionManager.h"
#import "BMSKeychain.h"
#import "BMSNetworkDefines.h"
#import "BMSEncryptionUtil.h"
#import "BMSAppInfoHelper.h"
#import <Foundation/NSURLSession.h>

@interface BMSAPIService()


@end

@implementation BMSAPIService

+ (void)fetchGameLaunchConfigWithVersion:(NSString *)version
                                 appName:(NSString *)appName
                                 success:(void(^)(id responseObject))success
                                 failure:(void(^)(NSError *error))failure {
    if (version.length == 0 || appName.length == 0) {
        if (failure) {
            NSError *error = [NSError errorWithDomain:@"BMSAPIService"
                                                 code:-1
                                             userInfo:@{NSLocalizedDescriptionKey: @"参数不完整"}];
            NSLog(@"[BMSAPIService] 参数校验失败: %@", error);
            failure(error); // ✅ 别忘了回调
        }
        return;
    }
    
    NSString *url = kLaunchGameConfigAPI;
    
    NSString *nonce = [BMSAppInfoHelper generateNonce];
    NSInteger timestamp = [BMSAppInfoHelper currentTimestamp];
    
    NSDictionary *params = @{
        kVersion: version,
        kApp_name: appName,
        kNonce: nonce,
        kTimeStamp: @(timestamp)
    };
    
    NSString *secret = kSecret;
    NSString *sign = [BMSEncryptionUtil generateSignWithParams:params secret:secret isRealAuth:NO];
    
    NSMutableDictionary *endParams = [NSMutableDictionary dictionaryWithDictionary:params];
    [endParams setValue:sign forKey:kSign];
    NSLog(@"[BMSAPIService] 请求启动配置: %@\n参数: %@", url, params);
    
    [[BMSNetworkSessionManager sharedManager] postWithURL:url
                                               parameters:params
                                                  success:success
                                                  failure:failure];
}

+ (void)fetchOfficialHolidaysWithSuccess:(void(^)(id responseObject))success
                                 failure:(void(^)(NSError *error))failure {
    NSString *url = kOfficialHolidayAPI;
    
    [[BMSNetworkSessionManager sharedManager] getWithURL:url
                                              parameters:nil
                                                 success:success
                                                 failure:failure];
}

+ (void)checkIPBlockStatusWithAppName:(NSString *)appName
                              channel:(NSString *)channel
                              version:(NSString *)version
                                   ip:(nullable NSString *)ip
                              success:(void(^)(NSDictionary *response))success
                              failure:(void(^)(NSError *error))failure {
    if (appName.length == 0 || channel.length == 0 || version.length == 0) {
        if (failure) {
            NSError *error = [NSError errorWithDomain:@"BMSAPIService"
                                                 code:-1
                                             userInfo:@{NSLocalizedDescriptionKey: @"参数不完整"}];
            failure(error);
        }
        return;
    }
    
    NSString *url = kIPBlockAPI;
    NSMutableDictionary *params = [@{
        kApp_name: appName,
        kChannel: channel,
        kVersion: version
    } mutableCopy];
    
    if (ip.length > 0) {
        params[@"ip"] = ip;
    }
    
    [[BMSNetworkSessionManager sharedManager] getWithURL:url
                                              parameters:params
                                                 success:success
                                                 failure:failure];
}

+ (void)submitRealnameWithName:(NSString *)name
                        idCard:(NSString *)idCard
                      zxbAppId:(nullable NSString *)zxbAppId
                       success:(void(^)(NSDictionary *response))success
                       failure:(void(^)(NSError *error))failure {
    if (name.length == 0 || idCard.length == 0) {
        if (failure) {
            NSError *error = [NSError errorWithDomain:@"BMSAPIService"
                                                 code:-1
                                             userInfo:@{NSLocalizedDescriptionKey: @"姓名或身份证不能为空"}];
            failure(error);
        }
        return;
    }
    
    NSString *url = kRealNameAuthAPI;
    NSMutableDictionary *params = [@{ @"name": name, @"id_card": idCard } mutableCopy];
    if (zxbAppId.length > 0) {
        params[@"zxb_app_id"] = zxbAppId;
    }
    NSString *nonce = [BMSAppInfoHelper generateNonce];
    NSInteger timestamp = [BMSAppInfoHelper currentTimestamp];
    
    [params setObject:nonce forKey:kNonce];
    [params setObject:@(timestamp) forKey:kTimeStamp];
    
    NSString *sign = [BMSEncryptionUtil generateSignWithParams:params secret:kSecret isRealAuth:YES];
    [params setObject:sign forKey:kSign];
    
    [[BMSNetworkSessionManager sharedManager] postWithURL:url
                                               parameters:params
                                                  success:^(id responseObject) {
        if (success) success(responseObject);
    } failure:failure];
}

+ (void)fetchUserSourceWithAppName:(NSString *)appName
                           version:(NSString *)version
                           channel:(NSString *)channel
                              uuid:(NSString *)uuid
                              idfa:(nullable NSString *)idfa
                              idfv:(nullable NSString *)idfv
                              imei:(nullable NSString *)imei
                              oaid:(nullable NSString *)oaid
                        android_id:(nullable NSString *)android_id
                           success:(void(^)(NSDictionary *response))success
                           failure:(void(^)(NSError *error))failure {
    if (appName.length == 0 || version.length == 0 || channel.length == 0 || uuid.length == 0) {
        if (failure) {
            NSError *error = [NSError errorWithDomain:@"BMSAPIService"
                                                 code:-1
                                             userInfo:@{NSLocalizedDescriptionKey: @"参数不完整"}];
            failure(error);
        }
        return;
    }
    
    NSString *url = kUserSourceAPI;
    NSMutableDictionary *params = [@{
        @"app_name": appName,
        @"version": version,
        @"channel": channel,
        @"uuid": uuid
    } mutableCopy];
    
    if (idfa.length) params[@"idfa"] = idfa;
    if (idfv.length) params[@"idfv"] = idfv;
    if (imei.length) params[@"imei"] = imei;
    if (oaid.length) params[@"oaid"] = oaid;
    if (android_id.length) params[@"android_id"] = android_id;
    
    [[BMSNetworkSessionManager sharedManager] postWithURL:url
                                               parameters:params
                                                  success:^(id responseObject) {
        if (success) success(responseObject);
    } failure:failure];
}

+ (void)loginWithOpenId:(NSString *)openid
                appName:(NSString *)appName
               platform:(NSString *)platform
                   idfa:(nullable NSString *)idfa
                   idfv:(nullable NSString *)idfv
                   imei:(nullable NSString *)imei
                   oaid:(nullable NSString *)oaid
                   adid:(nullable NSString *)adid
                    mac:(nullable NSString *)mac
                 serial:(nullable NSString *)serial
                success:(void(^)(NSDictionary *response))success
                failure:(void(^)(NSError *error))failure {

    if (openid.length == 0 || appName.length == 0 || platform.length == 0) {
        if (failure) {
            NSError *error = [NSError errorWithDomain:@"BMSAPIService"
                                                 code:-1
                                             userInfo:@{NSLocalizedDescriptionKey: @"参数不完整"}];
            failure(error);
        }
        return;
    }

    NSString *url = kSDKLoginAPI;
    NSMutableDictionary *params = [@{
        @"openid": openid,
        @"app_name": appName,
        @"platform": platform
    } mutableCopy];

    if (idfa.length) params[@"idfa"] = idfa;
    if (idfv.length) params[@"idfv"] = idfv;
    if (imei.length) params[@"imei"] = imei;
    if (oaid.length) params[@"oaid"] = oaid;
    if (adid.length) params[@"adid"] = adid;
    if (mac.length) params[@"mac"] = mac;
    if (serial.length) params[@"serial"] = serial;
    
    NSString *nonce = [BMSAppInfoHelper generateNonce];
    NSInteger timestamp = [BMSAppInfoHelper currentTimestamp];
    
    [params setObject:nonce forKey:kNonce];
    [params setObject:@(timestamp) forKey:kTimeStamp];
    
    NSString *sign = [BMSEncryptionUtil generateSignWithParams:params secret:kSecret isRealAuth:YES];
    [params setObject:sign forKey:kSign];


    [[BMSNetworkSessionManager sharedManager] postWithURL:url
                                                parameters:params
                                                   success:^(id responseObject) {
        if (success) success(responseObject);
    } failure:failure];
}

+ (void)uploadMergedReportWithParams:(NSDictionary *)params
                             traceId:(NSString *)traceId
                             success:(void(^)(id responseObject))success
                             failure:(void(^)(NSError *error))failure {

    NSString *trace = traceId ?: [[NSUUID UUID] UUIDString];
    NSString *url = [NSString stringWithFormat:@"/common/user-op/op-merge-report?trace_id=%@", trace];

    NSLog(@"[BMSReport] 🚀 开始上传合并上报:");
    NSLog(@"[BMSReport] 🔗 URL: %@", url);
    NSLog(@"[BMSReport] 🧾 参数: %@", params);
    NSLog(@"[BMSReport] 🧵 traceId: %@", trace);

    __block NSInteger maxRetryCount = 2;

    // 定义递归 block
    void (^__block performRequest)(NSInteger retryCount);
    performRequest = ^(NSInteger retryCount) {
        NSLog(@"[BMSReport] 🔁 尝试请求次数: %ld", (long)(retryCount + 1));

        [[BMSNetworkSessionManager sharedManager] postWithURL:url
                                                   parameters:params
                                                      success:^(id responseObject) {
            NSLog(@"[BMSReport] ✅ 上报成功: %@", responseObject);
            if (success) success(responseObject);
        } failure:^(NSError *error) {
            NSLog(@"[BMSReport] ❌ 第 %ld 次上报失败: %@\n🔁 traceId: %@", (long)(retryCount + 1), error.localizedDescription, trace);

            if (retryCount < maxRetryCount) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    performRequest(retryCount + 1);
                });
            } else {
                if (failure) failure(error);
            }
        }];
    };

    performRequest(0); // 初始从 retryCount = 0 开始
}

@end
